import Variable from "../constants/index";
import { ResponseData } from "../types/common";
import { HttpMethod } from "../types/enum";

export default class RequestHttp{
    static get<T>(url:string, params?:object){
        return request<T>(url,HttpMethod.GET,params)
    }
    static post<T>(url:string, params?:object){
        return request<T>(url,HttpMethod.POST,params)
    }
    static put<T>(url:string, params?:object){
        return request<T>(url,HttpMethod.PUT,params)
    }
    static delete<T>(url:string, params?:object){
        return request<T>(url,HttpMethod.DELETE,params)
    }
}
function request<T>(url:string, method:HttpMethod, data?:object){
    return new Promise<T>((resolve,reject)=>{
        wx.request<ResponseData<T>>({
            // 下面三个是请求需要传的参数，类型在common.d.ts定义了
            url: Variable.BASE_URL + url,
            method,
            data,
            // 
            success(res){
                // code是200代表成功
                if (res.data.code === 200) {
                    console.log(res);
                    
                    resolve(res.data.data)
                }else{
                    // 否则代表失败
                    wx.showToast({
                        title:res.data.msg,
                        icon:'error'
                    })
                    reject(new Error(res.data.msg))
                }
            },
            fail(res){
                reject(new Error(res.errMsg))
            }
        })
    })
}